import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import { connect } from 'dva'
import MusicAPI from '@/services/ant-design-pro/music';
import ProTable from '@ant-design/pro-table';

import CreateOrEdit from './components/MelodyAuthor/CreateOrEdit'
const { getMelodyAuthorList, deleteMelodyAuthor } = MusicAPI;
const MelodyAuthor = (props) => {
    const actionRef = useRef(); // 表格ref，便于自定义操作表格
    const { dispatch } = props;
    const [isModalVisible, setIsModalVisible] = useState(false),
        [editData, setEditData] = useState(undefined),
        [data, setData] = useState({});

    /**
     * 设置音乐数据到state
     * @returns obj(音乐列表)
     */
    const setMelodyAuthor = async () => {
        const result = await getMelodyAuthorList();
        setData(result.data.value);
        return {
            data: result.data.value,
            success: true
        }
    }


    /**
     * 控制模态框显示与隐藏
     */
    const isShowModal = (show, record = undefined) => {
        setIsModalVisible(show);
        setEditData(record);
    };

    const delMelodyAuthor = async (record) => {
        const result = await deleteMelodyAuthor({
            melody_author_id: record.melody_author_id
        })
        if (result.status == 'ok') {
            await setMelodyAuthor();
            actionRef.current.reload();
            message.success("删除成功");
            dispatch({
                type: 'music/refreshSelect',
                payload: {
                    key: 'MelodyAuthor',
                    refresh: true
                }
            });
        } else {
            message.error('删除失败：' + result.data.message);
            console.log(result.data.error);
        }
    }

    /**
     * 获取音乐列表
     * @param {obj} params 搜索参数
     * @returns obj(音乐列表)
     */
    const getData = (params) => {
        if (JSON.stringify(data) != "{}") {
            let melody_author_name = params.melody_author_name || "",
                result = data;
            if (melody_author_name.trim().length > 0) {
                result = data.filter((item, index) => {
                    return item.melody_author_name.toLowerCase().indexOf(melody_author_name.toLowerCase()) >= 0
                })
            }
            return {
                data: result,
                success: true
            }
        }
        return setMelodyAuthor();
    }


    const columns = [

        {
            title: '词作家名',
            dataIndex: 'melody_author_name',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: '操作',
            valueType: 'option',
            render: (text, record, _, action) => [
                <a rel="noopener noreferrer" key="edit" onClick={() => isShowModal(true, record)}>
                    编辑
                </a>,
                <a rel="noopener noreferrer" key="del" onClick={() => delMelodyAuthor(record)}>
                    删除
                </a>,
            ],
        },
    ];

    return (
        <PageContainer>
            <ProTable columns={columns} actionRef={actionRef} request={(params = {}, sort, filter) => {
                return getData(params);
            }}
                rowKey="melody_author_id"
                search={{
                    labelWidth: 'auto'
                }} pagination={{
                    pageSize: 5,
                }} dateFormatter="string" headerTitle="高级表格" toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => isShowModal(true)}>
                        新建
                    </Button>,
                ]} />
            {
                isModalVisible ?
                    <CreateOrEdit
                        isModalVisible={isModalVisible}
                        isShowModal={isShowModal}
                        actionRef={actionRef}
                        initData={editData}
                        setData={setMelodyAuthor}
                    /> : ""
            }
        </PageContainer>
    )
}

export default connect(({ music }) => ({ music }))(MelodyAuthor);